package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.PasswordConstant;
import com.sky.constant.StatusConstant;
import com.sky.context.BaseContext;
import com.sky.dto.EmployeeDTO;
import com.sky.dto.EmployeeLoginDTO;
import com.sky.dto.EmployeePageQueryDTO;
import com.sky.entity.Employee;
import com.sky.exception.BusinessException;
import com.sky.exception.DataException;
import com.sky.mapper.EmployeeMapper;
import com.sky.result.PageResult;
import com.sky.service.EmployeeService;
import com.sky.utils.BeanHelper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.RandomStringUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;

@Slf4j
@Api(tags = "员工管理")
@Service
public class EmployeeServiceImpl implements EmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    @ApiOperation("员工登入")
    @Override
    public Employee login(EmployeeLoginDTO employeeLoginDTO){
        String password = employeeLoginDTO.getPassword();
        String username = employeeLoginDTO.getUsername();
        //判断账号是否被锁定
        Object flag = redisTemplate.opsForValue().get("login:lock:" + username);
        if(ObjectUtils.isNotEmpty(flag)){
            log.info("账号被锁定一小时，请一小时后重新登入");
            throw new BusinessException(MessageConstant.LOGIN_LOCK_ERROR_MESSAGE);
        }


        //1.调用mapper,判断这个员工信息是否正确
        Employee employee = employeeMapper.findByUsername(employeeLoginDTO.getUsername());

        //2.判断员工是否存在，不在就返回错误信息
        if(employee == null){
            log.info("员工不存在");
            throw new DataException(MessageConstant.ACCOUNT_NOT_FOUND);
        }

        //先把明文加密成密文，再去比较数据库的密码
        password = DigestUtils.md5DigestAsHex(password.getBytes());

        //3.校验密码的正确性，如果不对，返回错误信息
        if(!password.equals(employee.getPassword())){
            log.info("密码错误");
            //3.1记录员工密码错误标记，并且设置5分钟有效期
            redisTemplate.opsForValue().set("login:" + username + ":" + RandomStringUtils.random(5)
                    , "-", 5, TimeUnit.MINUTES);

            //3.2获取员工错误次数，大于等于5次，锁定账号一小时
            Set<Object> keys = redisTemplate.keys("login:" + username + ":*");
            if(keys != null && keys.size() >= 5){
                log.info("用户五分钟内登入错误五次，锁定账号一小时");
                redisTemplate.opsForValue().set("login:lock:" + username, "-", 1, TimeUnit.HOURS);
                throw new BusinessException(MessageConstant.LOGIN_LOCK_ERROR);
            }

            throw new BusinessException(MessageConstant.PASSWORD_ERROR);

        }

        //4.判断状态，如果禁用，返回错误信息
        if(employee.getStatus() == StatusConstant.DISABLE){
            log.info("登入账号 {} 被禁用，请重新登入", employeeLoginDTO.getUsername());
            throw new BusinessException(MessageConstant.ACCOUNT_LOCKED);
        }

        return employee;
    }

    //新增员工
    @Override
    public void save(EmployeeDTO employeeDTO) {
        //属性拷贝
        Employee employee = BeanHelper.copyProperties(employeeDTO, Employee.class);

        //1.设置密码
        employee.setPassword(DigestUtils.md5DigestAsHex(PasswordConstant.DEFAULT_PASSWORD.getBytes()));

        //2.设置初始状态
        employee.setStatus(StatusConstant.ENABLE);

        //3.设置创建时间和修改时间
//        employee.setCreateTime(LocalDateTime.now());
//        employee.setUpdateTime(LocalDateTime.now());
//        //设置员工id
//        employee.setCreateUser(BaseContext.getCurrentId());
//        employee.setUpdateUser(BaseContext.getCurrentId());

        employeeMapper.insert(employee);

    }


    @Override
    public PageResult page(EmployeePageQueryDTO pageQueryDTO) {
        //1.设置分页参数
        PageHelper.startPage(pageQueryDTO.getPage(),pageQueryDTO.getPageSize());
        //2.执行查询
        List<Employee> employeeList = employeeMapper.list(pageQueryDTO.getName());
        //3.解析并封装
        Page<Employee> page = (Page<Employee>) employeeList;

        return new PageResult(page.getTotal(), page.getResult());
    }

    //启用禁用员工账号
    @Override
    public void startOrStop(Integer status, Long id) {
        Employee employee = Employee.builder()
                .status(status)
                .id(id)
//                .updateTime(LocalDateTime.now())
//                .updateUser(BaseContext.getCurrentId())
                .build();

        employeeMapper.update(employee);
    }


}
